package com.beone.admin.controller.base;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.base.SuperController;
import com.beone.admin.annotation.Log;
import com.beone.admin.common.AdminConstants;
import com.beone.admin.controller.ControllerUtils;
import com.beone.admin.entity.BasePermission;
import com.beone.admin.exception.MvcException;
import com.beone.admin.security.filter.PermissionsGrantedAuthority;
import com.beone.admin.service.BasePermissionService;

import com.beone.admin.utils.ServiceUtils;
import com.beone.admin.utils.result.ResultCode;
import com.beone.admin.utils.result.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Title 运维数据_系统菜单功能权限表 前端控制器
 * @Author 覃球球
 * @Version 1.0 on 2018-01-25
 * @Copyright 长笛龙吟
 */
@Controller
@RequestMapping("/system/permission")
@Api(value = "权限管理模块", tags = {"权限管理接口"})
public class BasePermissionController extends SuperController {
    private static final Logger log = LoggerFactory.getLogger(BasePermissionController.class);

    @Autowired
    private BasePermissionService permissionService;

    /**
     * 后台权限管理入口 -> index
     *
     * @return
     */
    @GetMapping("")
    public String index() {
        return "base/permission/index";
    }

    /**
     * 后台权限管理显示添加页面 -> showAdd
     *
     * @return
     */
    @GetMapping("/showAdd")
    public String showAdd() {
        return "base/permission/form";
    }

    /**
     * 后台权限管理显示添加页面 -> showAdd
     *
     * @return
     */
    @GetMapping("/showUpdate")
    public String showUpdate(Integer nodeId, ModelMap model) throws MvcException {
        try{
            model.addAttribute("nodeId", nodeId);
            model.addAttribute("permission", permissionService.getPermissionByNodeId(nodeId));
        }catch (Exception e){
            log.error("showUpdate 异常 e = {}", e);
            throw new MvcException(e.getMessage());
        }
        return "base/permission/form";
    }

    /**
     * 根据主键查询权限，用于分页展示权限管理
     *
     * @return 所匹配的权限信息，适用于easyui-tree的json字符串

     @RequestMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
     @ResponseBody public Object queryPermissions(HttpServletRequest request,
     @RequestParam(value = "page", defaultValue = AdminConstants.DEFAULT_PAGE_NUM) int currPage,
     @RequestParam(value = "rows", defaultValue = AdminConstants.PAGE_SIZE) int pageSize) {
     String id = request.getParameter("id");
     String nodeName = request.getParameter("nodeName");
     return permissionService.getPermissionPagination(id, nodeName, currPage, pageSize);
     }*/

    /**
     * 获取所有权限信息
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "权限列表", notes = "权限列表查询")
    @ApiImplicitParam(name = "type", value = "type=page 获取所有可用菜单权限  否则获取全部权限", required = false
            , paramType = "query", dataType = "string")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object queryPermissions(HttpServletRequest request) {
        List<BasePermission> list = null;
        String type = request.getParameter("type");
        if ("page".equals(type)) { //只获取权限类型为页面菜单
            list = permissionService.getAllPermissionses(type);
        } else { //获取权限
            list = permissionService.selectList(new EntityWrapper<BasePermission>());
        }
        return ServiceUtils.createGatagridTableJson(null, list);
    }


    /**
     * 显示后台首页页面菜单树
     *
     * @return
     */
    @ApiOperation(value = "获取用户分配菜单权限", notes = "获取用户分配菜单权限")
    @PostMapping(value = "/indexMenuTree", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object showHomePageMenu(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String sessionKey = "userPermission";
        Collection<BasePermission> permissions = (Collection<BasePermission>)
                session.getAttribute(sessionKey);
        if (permissions == null) {
            //获取登录用户拥有的权限资源
            Collection<PermissionsGrantedAuthority> collection = (Collection<PermissionsGrantedAuthority>)
                    ControllerUtils.getSysUserPermissions(request).getAuthorities();
            List<BasePermission> userPermisList = new ArrayList<BasePermission>();
            for (PermissionsGrantedAuthority adminPermissions : collection) {
                BasePermission userPermissions = adminPermissions.getPermissions();
                if (StringUtils.isNotBlank(userPermissions.getTypeNode())
                        && "03".equals(userPermissions.getTypeNode())) { //权限为菜单资源
                    BasePermission newPermiss = new BasePermission();
                    //避免对象循环依赖 new 新对象
                    BeanUtils.copyProperties(userPermissions, newPermiss);
                    userPermisList.add(newPermiss);
                }
            }
            permissions = userPermisList;
            //用户权限添加到Session 会话
            session.setAttribute(sessionKey, permissions);
        }
        return permissions;
    }

    /**
     * 显示所有(菜单和功能)可用权限信息
     *
     * @return
     */
    @ApiOperation(value = "获取可用权限", notes = "used参数为page 获取所有可用菜单权限  否则获取所有可用权限")
    @ApiImplicitParam(name = "used", value = "用户详细实体user", required = true
            , paramType = "path", dataType = "string")
    @PostMapping("/all/{used}")
    @ResponseBody
    public Object showAll(@PathVariable("used") String used) {
       /* //显示所有可见的菜单权限
        Collection<BasePermission> allPermission=permissionService.showPermissionMenuTree("all", used);
        for (BasePermission permissions : allPermission) {
            if("index".equals(permissions.getNodeCode()) ||  //默认勾选后台首页
                    "leftMenuTree".equals(permissions.getNodeCode())){ //默认勾选后台左侧导航树
                permissions.setChecked(true);
            }
        }*/
        return ServiceUtils.createGatagridTableJson(null
                , permissionService.getAllPermissionses(used));
    }

    /**
     * 启用/禁用权限
     *
     * @param nodeId 权限id
     * @param status 更新当前状态  1 启用 0 禁用
     * @return 操作结果
     */
    @PostMapping("/status")
    @ResponseBody
    public Object status(Integer nodeId, Integer status) {
        BasePermission access = new BasePermission();
        access.setNodeId(nodeId);
        access.setIsIndex(status);
        if (permissionService.updateById(access)) {
            return ResultUtils.success();
        }
        return ResultUtils.warn(ResultCode.FAIL);
    }

    /**
     * 保存权限
     *
     * @param permissions 权限信息
     * @return 保存权限
     */
    @Log(desc = "权限", type = Log.LOG_TYPE.SAVE)
    @ApiOperation(value = "保存权限", notes = "保存权限信息 主键属性为空新增,否则修改")
    @ApiImplicitParam(name = "permissions", value = "权限详细实体", required = true
            , paramType = "form", dataType = "object")
    @PostMapping("/savePermiss")
    @ResponseBody
    public Object savePermiss(BasePermission permissions) {
        if (permissionService.savePermissions(permissions)) {
            return ResultUtils.success();
        }
        return ResultUtils.warn(ResultCode.FAIL);
    }

    /**
     * 根据权限Id 删除权限
     *
     * @param nodeId 权限id
     * @return 操作结果
     */
    @Log(desc = "删除权限", type = Log.LOG_TYPE.DEL)
    @ApiOperation(value = "删除权限", notes = "根据权限Id，删除权限")
    @ApiImplicitParam(name = "nodeId", value = "权限ID", required = true, paramType = "param", dataType = "int")
    @PostMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object status(Integer nodeId) {
        if (permissionService.deleteById(nodeId)) {
            return super.responseResult("success", "成功!");
        }
        return super.responseResult("fail", "失败!");
    }
}

